/*
 * adc.c
 *
 *  Created on: 2025年3月30日
 *      Author: ceeu
 */

/* Private includes ----------------------------------------------------------*/
#include "adc.h"
#include "Cpu.h"
/* Private typedef -----------------------------------------------------------*/

/* Private define ------------------------------------------------------------*/
#define ADC_VREFH 3.3f
#define ADC_VREFL 0.0f

/* Private macro -------------------------------------------------------------*/

/* Private variables ---------------------------------------------------------*/
float    adcValue;
uint16_t adcRawValue[10];
uint16_t adcMax;

uint32_t adcRawConversions;
/* Private function prototypes -----------------------------------------------*/

/* Private user code ---------------------------------------------------------*/
void ADC0_IRQHandler(void) {
    if (ADC_DRV_GetConvCompleteFlag(INST_ADCONV0, 0)) {
        adcRawConversions++;
        // ADC_DRV_GetChanResult(INST_ADCONV0, 0, &adcRawValue);
    }
}

void ADC0_Init(void) {
    // Initialize ADC
    if (adConv0_ConvConfig0.resolution == ADC_RESOLUTION_8BIT) {
        adcMax = (uint16_t)(1 << 8);
    }
    else if (adConv0_ConvConfig0.resolution == ADC_RESOLUTION_10BIT) {
        adcMax = (uint16_t)(1 << 10);
    }
    else if (adConv0_ConvConfig0.resolution == ADC_RESOLUTION_12BIT) {
        adcMax = (uint16_t)(1 << 12);
    }
    else {
        adcMax = (uint16_t)(1 << 12);
    }
    ADC_DRV_ConfigConverter(INST_ADCONV0, &adConv0_ConvConfig0);
    ADC_DRV_AutoCalibration(INST_ADCONV0);

    ADC_DRV_ConfigChan(INST_ADCONV0, 0UL, &adConv0_ChnConfig0);
    ADC_DRV_ConfigChan(INST_ADCONV0, 1UL, &adConv0_ChnConfig1);
    ADC_DRV_ConfigChan(INST_ADCONV0, 2UL, &adConv0_ChnConfig2);
    ADC_DRV_ConfigChan(INST_ADCONV0, 3UL, &adConv0_ChnConfig3);
    ADC_DRV_ConfigChan(INST_ADCONV0, 4UL, &adConv0_ChnConfig4);
    ADC_DRV_ConfigChan(INST_ADCONV0, 5UL, &adConv0_ChnConfig5);
    ADC_DRV_ConfigChan(INST_ADCONV0, 6UL, &adConv0_ChnConfig6);
    ADC_DRV_ConfigChan(INST_ADCONV0, 7UL, &adConv0_ChnConfig7);

    INT_SYS_InstallHandler(ADC0_IRQn, &ADC0_IRQHandler, (isr_t *)0U);
    // INT_SYS_EnableIRQ(ADC0_IRQn);
}

float adc0_ch2_read(void) {
    adcValue = (float)adcRawValue[0] * (ADC_VREFH - ADC_VREFL) / adcMax + ADC_VREFL;
    return adcValue;
}

float adc0_ch3_read(void) {
    adcValue = (float)adcRawValue[1] * (ADC_VREFH - ADC_VREFL) / adcMax + ADC_VREFL;
    return adcValue;
}
